package com.ruoyi.mobile.api;


import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.deepoove.poi.XWPFTemplate;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResults;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.qsng.domain.KCoursePurchase;
import com.ruoyi.qsng.service.IKCoursePurchaseService;
import com.ruoyi.qsng.service.IKUsersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 *查看收据返回图片
 */
@Api(tags = "查看收据返回图片")
@RestController
@RequestMapping
@Slf4j
public class WordPastPhotoController {

    @Autowired
    private ServerConfig serverConfig;

    @Autowired

    private RuoYiConfig ruoYiConfig;

    @Autowired
    private IKCoursePurchaseService kCoursePurchaseService;

    @ResponseBody
    @ApiOperation(value = "word转图片（查看收据）")
    @RequestMapping("/app/receipt/{orderId}")
    public AjaxResults getReceipt(@PathVariable("orderId") String orderId) throws Exception {
        // word文档名称，我把他放在项目resources文件下
        Assert.notNull(orderId, "获取订单id失败！" );
        KCoursePurchase kCoursePurchase =kCoursePurchaseService.selectKCoursePurchaseById(orderId);
        Assert.notNull(kCoursePurchase, "获取订单失败！");

        String name = "tmpt.docx";
        // 读取resources文件下 Word 模板文件
        InputStream ins = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
        // 使用模板引擎将模板渲染，并传入一个数据映射表 initWordMap()。
        XWPFTemplate template = XWPFTemplate.compile(ins).render(initWordMap(kCoursePurchase.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(),kCoursePurchase.getNameWX()));

        String tmpFilePath = ruoYiConfig.getProfile() + "/tmpltJpg.docx";
        // 填充完数据后保持到上面路径
        template.writeToFile(tmpFilePath);
        UUID uuid = UUID.randomUUID();
        String jpgFilePath = ruoYiConfig.getProfile() +"/" + UUID.randomUUID().toString()+".jpeg";

        Document doc = new Document(new FileInputStream(new File(tmpFilePath)));
        // 将 Word 文件保存为图片（JPEG格式）
        doc.save(jpgFilePath, SaveFormat.JPEG);
        int dirLastIndex = RuoYiConfig.getProfile().length() + 1;
        // 截取cert/test.jpeg
        String currentDir = StringUtils.substring(jpgFilePath, dirLastIndex);
        // 拼接路径
        String imagesPath =  ruoYiConfig.getAddressPort() + Constants.RESOURCE_PREFIX + "/" + currentDir;
        System.out.println(imagesPath);
        return AjaxResults.success(imagesPath);
    }
    /**
     * word文档需要填充的数据
     * @return
     */
    private static Map<String, Object> initWordMap(double a,String name) {
        Map<String, Object> wordData = new HashMap<>();
//        double a = 20;
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy年MM月dd日");
        Date date = new Date();
        String formattedDate = sdf.format(date);
        wordData.put("date", formattedDate);
        wordData.put("name", name);//当前登录人的姓名
        wordData.put("content", "课时费:"+a+"元");//"课时费"是固定写法，钱数是缴费的钱数；
        wordData.put("money", upperCase2(a));//a 是double类型的钱数
        wordData.put("entprise", "霍尔果斯市青少年活动中心");//固定值，不用变
        return wordData;
    }
    public static String upperCase2(double money){
        String[] upNum = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
        String[] danwei = {"元","拾","佰","仟","万","拾","佰","仟","亿","拾","佰","仟"};
        //取消科学记数法
        NumberFormat numFormat = NumberFormat.getInstance();
        numFormat.setMaximumFractionDigits(2);//设置小数位个数
        numFormat.setGroupingUsed(false);//取消科学技术发
        String formatNum = numFormat.format(money);
        String strmoney = formatNum + "";//浮点型转为字符型
        String lastUpNum = "null"; //用于存放上个参数的值
        String result = "";//返回的结果
        String[] split = strmoney.split("\\.");
        String strMoney = split[0];
        String point = "";
        //小数部分取值处理。
        if(split.length>1){
            point = split[1];
            if(point.length()==1){
                point = point.concat("0");
            }
        }else {
            point = "0";
        }
        //大于12位就直接返回。
        int moneyLen = strMoney.length();
        if(money==0){
            return "零元整";
        }
        if(moneyLen>12){
            return "金额："+money+"元，超出大写转换范围。最大金额：999999999999.99元";
        }
        //整数(integer)部分处理。
        if(!"0".equals(strMoney)){
            for (int i = 0; i < moneyLen; i++) {
                String strNum = strMoney.charAt(i)+"";
                int singleNum = Integer.parseInt(strNum);
                String upSingleNum = upNum[singleNum];
                //上一为不等于0的情况
                if(!"零".equals(lastUpNum)){
                    if(!"零".equals(upSingleNum)){
                        result = result.concat(upSingleNum).concat(danwei[moneyLen-i-1]);
                    }else
                        //为零但是在万、亿位上要加单位 (moneyLen-i)==9 指的是单位：亿。  (moneyLen-i)==5指的是单位：万
                        if( (moneyLen-i)==5 || (moneyLen-i)==9 ){
                            lastUpNum="";
                        }else {
                            result=result.concat(upSingleNum);
                        }
                }
                //上一位为0的情况
                if("零".equals(lastUpNum) && !"零".equals(upSingleNum)){
                    result = result.concat(upSingleNum).concat(danwei[moneyLen-i-1]);
                }
                //捕捉上一位数（lastUpNum）为零的情况做优化。
                if((moneyLen-i)==5 || (moneyLen-i)==9 ){
                    //排除加单位时前面为"零"的情况。如：两百零万
                    if("零".equals(lastUpNum)||"null".equals(lastUpNum)){
                        result = result.substring(0,result.length()-1);
                    }
                    if(!result.endsWith("亿")){
                        result = result.concat(danwei[moneyLen-i-1]);
                    }
                    lastUpNum="";
                }else {
                    //把当前大写数字复制给 lastUpNum 用于下次判断
                    lastUpNum = upSingleNum;
                }
            }
            //对几万元整和几亿元整(result:五万零或者五亿零零)做优化。
            result=result.replaceAll("零零","零");
            if(result.endsWith("零")){
                String substring = result.substring(0,result.length() - 1);
                result = substring;
            }
            result = result.concat("元");
            result = result.replaceAll("元元","元");
            result = result.replaceAll("万万","万");

        }

        //小数(point)部分处理
        if("0".equals(point)){
            result =  result+"整";
        }else {
            if((point.charAt(0)+"").equals("0")){
                result = result.concat(upNum[Integer.parseInt(point.charAt(1)+"")]+"分");
            }else if((point.charAt(1)+"").equals("0")){
                result = result.concat(upNum[Integer.parseInt(point.charAt(0)+"")]+"角");
            }else {
                result = result.concat(upNum[Integer.parseInt(point.charAt(0)+"")]+"角").concat(upNum[Integer.parseInt(point.charAt(1)+"")]+"分");
            }
        }
        return result;
    }


}
